var ns, WXPhotoPicker;
app = new Vue({
    el: '#app',
    data: {
        newform: {
            TaskType: '',
            TaskTypeName:'',
            TaskChargeUser: 0,
            TaskChargeUserName: '',
            TaskStartTime: '',
            TaskEndTime: '',
            Title: '',
            TaskContent: '',
            TaskMoreUser: [],
            TaskTag: [],
            TaskStatus:1,
        },
        ID: 0,
        DelImgIDs:[],
        task_imgList:[],
        imglist: [],
        ProjectList: [],
        maxuploadcount: CONFIG.maxuploadcount,
        //任务类型
        IsTaskTypeOpen: false,
        TaskTypeList: [],
         //任务标签
         IsTaskTagOpen: false,
         TaskTagList: [],     
    },
    methods: {
        get_data(){
            var that = this;
            var options = {};
            options.ID = that.ID;    
            options.action = "getworktaskdetail";
            ns.post(options, function (succeed, data, err) {
                // console.log(JSON.stringify(data));
                if (succeed) {
                    var form=data.data;
                    that.newform.TaskType = form.TypeID;
                    that.newform.TaskTypeName=form.TypeName;
                    that.newform.TaskChargeUser = form.HandleUserID;
                    that.newform.TaskChargeUserName = form.HandleUserName;
                    that.newform.TaskStartTime = moment(form.StartTime).format('YYYY-MM-DD HH:mm');
                    that.newform.TaskEndTime = moment(form.EndTime).format('YYYY-MM-DD HH:mm');
                    that.newform.Title = form.Title;
                    that.newform.TaskContent = form.NoteDesc;
                    that.newform.TaskStatus = form.Status;
                    //参与人
                    that.newform.TaskMoreUser = [];
                    if (form.PartakeUserList&&form.PartakeUserList.length>0) {
                        var newData = [];
                        form.PartakeUserList.forEach((item) => {
                            var newmodel = { UserID: item.UserID, FinalRealName: item.UserName, HeadImg: item.HeadImg };
                            newData.push(newmodel);
                        });
                        that.newform.TaskMoreUser=newData;
                    }
                    //任务标签
                    that.newform.TaskTag = [];
                    if (form.TagList && form.TagList.length > 0) {
                        var newTagData = [];
                        form.TagList.forEach((item) => {
                            var newtagmodel = { ID: item.WorkTaskTagID, Name: item.TagName };
                            newTagData.push(newtagmodel);
                            var findIndex = that.TaskTagList.findIndex((val) => {
                                return val.ID == item.WorkTaskTagID;
                            });
                            if (findIndex > -1) {
                                that.TaskTagList[findIndex].IsSelected = true;
                            }
                        });
                        that.newform.TaskTag = newTagData;
                    }
                    //附件
                   that.task_imgList=form.FileList;
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true
            });
        },
        getworktaskother: function () {
            var that = this;
            var options = {};
            options.action = "getworktasksearchdata";
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    that.TaskTypeList = data.data.TypeList;
                   let newTaglist = data.data.TagList;
                    if(newTaglist&&newTaglist.length>0){
                       let returnlist=newTaglist.map((val)=>{
                            val.IsSelected=false;
                            return val;
                        });
                        that.TaskTagList=returnlist;
                    }
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
        },  
        do_save: function (type) {
            var that = this;
            if (that.newform.TaskType==''||that.newform.TaskType<=0) {
                api.toast({
                    msg: '请选择任务类型',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.TaskChargeUser == ''||that.newform.TaskChargeUser<=0) {
                api.toast({
                    msg: '请选择负责人',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.TaskStartTime == '') {
                api.toast({
                    msg: '请选择开始时间',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.TaskEndTime == '') {
                api.toast({
                    msg: '请选择结束时间',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            const diffStartTime = moment(that.newform.TaskEndTime).diff(moment(that.newform.TaskStartTime), 'seconds');
             if (diffStartTime <= 0) {
                api.toast({
                    msg: '任务开始时间不能大于等于结束时间',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.Title == '') {
                api.toast({
                    msg: '请填写任务标题',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            that.do_save_process(type);
        },
        do_save_process: function (type) {
            var that = this;
            var filelist = [];
            for (var i = 0; i < that.imglist.length; i++) {
                if (that.imglist[i].isupload) {
                    filelist.push(that.imglist[i].url);
                }
            }
            var options = {};
            options.ID = that.ID;   
            options.Status = type; //1-暂存  2-保存&发布
            options.action = "saveworktask";
            options.TypeID = that.newform.TaskType;    
            options.HandleUserID = that.newform.TaskChargeUser;   
            options.StartTime = that.newform.TaskStartTime;   
            options.EndTime = that.newform.TaskEndTime;   
            options.Title = that.newform.Title;   
            options.NoteDesc = that.newform.TaskContent;   
             //参与人
             var TaskMoreUsers = [];
             if (that.newform.TaskMoreUser.length > 0) {
                that.newform.TaskMoreUser.forEach((item) => {
                     TaskMoreUsers.push(item.UserID);
                 });
             }
            options.PartakeUserIDs = JSON.stringify(TaskMoreUsers);   
              //任务标签
              var TaskTags = [];
              if (that.newform.TaskTag.length > 0) {
                    that.newform.TaskTag.forEach((item) => {
                      TaskTags.push(item.ID);
                  });
              }
            options.TagIDs = JSON.stringify(TaskTags);
            options.DeleteFileIDs = JSON.stringify(that.delFileIDs);
            // console.log(JSON.stringify(options));
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    if (data.status) {
                        api.toast({
                            msg: '操作成功',
                            duration: 2000,
                            location: 'bottom'
                        });
                        api.sendEvent({
                            name: 'updata_task_detail',
                        });
                        api.sendEvent({
                            name: 'reloadworktasklist',
                        });
                        //关闭-详情页面-关闭指定window，若待关闭的window不在最上面，则无动画
                        api.closeWin({
                            name: 'worktaskdetail_frm'
                        });
                        setTimeout(function () {
                            api.closeWin();
                        }, 300)
                        return
                    }
                    else if (data.error) {
                        api.toast({
                            msg: data.error,
                            duration: 3000,
                            location: 'bottom'
                        });
                    }

                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true,
                files: {
                    file: filelist
                }
            });
        },
        do_close(){
            api.closeWin();
        },
        //上传图片
        choose_picture: function () {
            var that = this;
            ns.confirmPer('camera', function () {
                that.choose_picture_start();
            })
        },
        choose_picture_start:function(){
            var that = this;
            if (that.imglist.length >= that.maxuploadcount) {
                api.toast({
                    msg: '最多支持' + that.maxuploadcount + '张图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            api.actionSheet({
                cancelTitle: '取消',
                buttons: ['拍照', '从相册选择']
            }, function(ret, err) {
                //拍照
                if(ret.buttonIndex==1){ 
                    that.upload_choose_picture();
                    return;
                }
                //从相册选择
                if(ret.buttonIndex==2){
                    that.choose_picture_album();
                    return;
                } 
                //取消 
                else{
                    return false;  
                }  
            });
        },
        upload_choose_picture:function(){
            var that = this;
            api.getPicture({
                sourceType: 'camera',
                encodingType: 'jpg',
                destinationType: 'url',
                allowEdit: false,
                saveToPhotoAlbum: true,
            }, function(ret, err) {
                if (ret&&ret.data) {
                    that.imglist.push({
                        ID: 0,
                        url: ret.data,
                        thumbPath: ret.data,
                        isupload: true
                    });
                } 
            });
        },
        choose_picture_album:function(){
            var that = this;
            WXPhotoPicker.open({
                max: that.maxuploadcount - that.imglist.length,
                type:'image',
            }, function(ret) {
                if (ret) {
                    if (ret.list.length > 0) {
                        ret.list.forEach((item) => {
                            that.imglist.push({
                                ID: 0,
                                url: item.path,
                                thumbPath: item.path,
                                isupload: true
                            });
                        });
                    }
                }
            });
        },
        remove_img: function (index,item) {
            var that = this;
            that.imglist.splice(index, 1);
        },
        do_viewimages: function (activeIndex) {
            var that = this;
            var imageUrls = [];
            for (var i = 0; i < that.imglist.length; i++) {
                imageUrls.push(that.imglist[i].url);
            }

            var imageBrowser = api.require('imageBrowser');
            imageBrowser.openImages({
                showList: false,
                activeIndex: activeIndex,
                imageUrls: imageUrls
            });
        },
        //负责人
        doChooseHandleUser(){
            var that = this;
            ns.openWin('repairchooseuser', '选择负责人', {
                IsMultiple:false,//是否多选
                IsChoose:true,//是否只选择
            });
        },
         //参与人
         doChoosePartakeUser(){
            var that = this;
            ns.openWin('repairchooseuser', '选择参与人', {
                IsMultiple:true,
                IsChoose:true,
            });
        },
         doRemoveUser:function(item,index){
            var that=this;
            // that.selectUserlist = that.selectUserlist.filter((item) => {
            //     return item.UserID != id
            // });
            that.newform.TaskMoreUser.splice(index, 1);
        },
        //选择任务类型
        doTaskTypeOpen: function () {
            var that = this;
            that.IsTaskTypeOpen = true;
        },
        doCloseTaskType: function () {
            var that = this;
            that.IsTaskTypeOpen = false;
        },
        doSelectTaskType: function (item) {
            var that = this;
            that.IsTaskTypeOpen = false;
            that.newform.TaskType = item.ID;
            that.newform.TaskTypeName = item.Name;
        },
         //选择任务标签
        doTaskTagOpen: function () {
            var that = this;
            that.IsTaskTagOpen = true;
        },
        doCloseTaskTag: function () {
            var that = this;
            that.IsTaskTagOpen = false;
            that.TaskTagList.forEach( (item) => {
                item.IsSelected=false;
                var findIndx=that.newform.TaskTag.findIndex((val)=>{
                    return val.ID==item.ID;
                });
                if(findIndx>-1){
                    item.IsSelected=true;
                }
            });
        },
        doRemoveTaskTag(item,index){
            var that = this;
            that.newform.TaskTag.splice(index, 1);
            that.TaskTagList.forEach( (val) => {
                if(val.ID==item.ID){
                    item.IsSelected=false;
                }
            });
        },
        doSelectTaskTag: function (item) {
            var that = this;
            item.IsSelected = !item.IsSelected;
        },
        doSelectTaskTagOk(){
            var that = this;
            let result = that.TaskTagList.filter( (val) => {
                return val.IsSelected;
            });
            that.newform.TaskTag=result;
            that.IsTaskTagOpen = false;
        },
        //编辑-附件
        remove_img_edit: function (ID) {
            var that = this;
            for (var i = 0; i < that.task_imgList.length; i++) {
                var item = that.task_imgList[i];
                if (item.ID == ID) {
                    that.DelImgIDs.push(ID);//保存需要删除的图片ID
                    that.task_imgList.splice(i, 1);
                }
            }
        },
        do_viewimages_edit: function (activeIndex) {
            var that = this;
            var imageUrls = [];
            for (var i = 0; i < that.task_imgList.length; i++) {
                imageUrls.push(that.task_imgList[i].SysFinalFilePath);
            }
            var imageBrowser = api.require('imageBrowser');
            imageBrowser.openImages({
                showList: false,
                activeIndex: activeIndex,
                imageUrls: imageUrls
            });
        },
        initPicker: function () {
            var _this = this;
            (function ($, doc) {
                $.init();
                $.ready(function () {
                    //开始
                    var btn = document.querySelector('#choosedatestarttime');
                    btn.addEventListener('tap', function () {
                        var _self = this;
                        if (_self.picker) {
                            if(_this.newform.TaskStartTime){
                                _self.picker.setSelectedValue(_this.newform.TaskStartTime);//回显
                            }
                            _self.picker.show(function (rs) {
                                _this.newform.TaskStartTime = rs.value;
                                _self.picker.dispose();
                                _self.picker = null;
                            });
                        } else {
                            var optionsJson = this.getAttribute('data-options') || '{}';
                            var options = JSON.parse(optionsJson);
                            var id = this.getAttribute('id');
                            _self.picker = new $.DtPicker(options);
                            if(_this.newform.TaskStartTime){
                                _self.picker.setSelectedValue(_this.newform.TaskStartTime);//回显
                            }
                            _self.picker.show(function (rs) {
                                var timer = setTimeout(function () {
                                    clearTimeout(timer);
                                    _this.newform.TaskStartTime = rs.value;
                                }, 300);
                                _self.picker.dispose();
                                _self.picker = null;
                            });
                        }
                    }, false);
                    //结束
                    var btnEnd = document.querySelector('#choosedateendtime');
                    btnEnd.addEventListener('tap', function () {
                        var _self = this;
                        if (_self.picker) {
                            if(_this.newform.TaskEndTime){
                                _self.picker.setSelectedValue(_this.newform.TaskEndTime);//回显
                            }
                            _self.picker.show(function (rs) {
                                _this.newform.TaskEndTime = rs.value;
                                _self.picker.dispose();
                                _self.picker = null;
                            });
                        } else {
                            var optionsJson = this.getAttribute('data-options') || '{}';
                            var options = JSON.parse(optionsJson);
                            var id = this.getAttribute('id');
                            _self.picker = new $.DtPicker(options);
                            if(_this.newform.TaskEndTime){
                                _self.picker.setSelectedValue(_this.newform.TaskEndTime);//回显
                            }
                            _self.picker.show(function (rs) {
                                var timer = setTimeout(function () {
                                    clearTimeout(timer);
                                    _this.newform.TaskEndTime = rs.value;
                                }, 300);
                                _self.picker.dispose();
                                _self.picker = null;
                            });
                        }
                    }, false);

                });
            })(mui, document);
        },
    }
});
apiready = function () {
    api.parseTapmode();
    ns = window.Foresight.Util;
    WXPhotoPicker = api.require('WXPhotoPicker');
    app.ID = api.pageParam.ID || 0;

    app.initPicker()
    app.getworktaskother();
    if(app.ID>0){
        app.get_data();
    }

    api.addEventListener({
        name: 'choose_user_one'
    }, function (ret, err) {
        if(ret.value.data){
            app.newform.TaskChargeUser=ret.value.data[0].UserID;
            app.newform.TaskChargeUserName=ret.value.data[0].FinalRealName;
        } 
    });
    api.addEventListener({
        name: 'choose_user_more'
    }, function (ret, err) {
        app.newform.TaskMoreUser=ret.value.data;
    });
};
